<?php
/*********************************************
 *  CPG Dragonfly™ CMS
 *********************************************
	Copyright © since 2010 by CPG-Nuke Dev Team
	http://dragonflycms.org

	Dragonfly is released under the terms and conditions
	of the GNU GPL version 2 or any later version
*/

namespace Poodle;

abstract class URI
{

	public static function resolve($uri='', $query=null)
	{
		if ($uri)
		{
			if ('?' === $uri[0]) {
				$s = substr($uri,0,10);
				if ('?admin&op='===$s) {
					return str_replace('&amp;','&',\URL::admin(substr($uri,10)));
				}
			}
			else if ('cdn://' === substr($uri,0,6)) {
				$uri = substr($uri, 6);
				if ('theme/' === substr($uri,0,6)) {
					return DF_STATIC_DOMAIN . THEME_PATH . substr($uri,6);
				}
				return DF_STATIC_DOMAIN . $uri;
			}
		}
		return $uri;
	}

	public static function index($str)
	{
		return \URL::index($str);
	}

	/**
	 * Workaround, because parse_str() converts dots and spaces in variable
	 * names to underscores, as noted on http://php.net/parse_str
	 * and on http://php.net/manual/en/language.variables.external.php
	 */
	public static function parse_query($str)
	{
		if (is_array($str)) return $str;
		$data = array();
		if (is_string($str))
		{
			$parts = explode('&', $str);
			foreach ($parts as $part)
			{
				$pair = explode('=', $part, 2);
				if (2 == count($pair)) {
					$data[urldecode($pair[0])] = urldecode($pair[1]);
				} else {
					$data[urldecode($part)] = '';
				}
			}
		}
		return $data;
	}

	public static function shrink($uri, $len=35)
	{
		$uri = preg_replace('#^[a-z]+?://#i', '', $uri);
		return (strlen($uri) > $len) ? substr($uri,0,round($len*2/3)).'...'.substr($uri,3-round($len/3)) : $uri;
	}

	public static function encode($uri)
	{
		return preg_replace('#([\x20\x22\x3C\x3E])#e', '\'%\'.bin2hex(stripslashes(\'$1\'))', $uri);
	}

	public static function redirect($uri='', $code=303)
	{
		\URL::redirect(self::resolve($uri), false, $code);
	}

	public static function appendArgs($uri, array $args)
	{
		$uri_q = parse_url($uri, PHP_URL_QUERY);
		if ($uri_q) { $args = array_merge(self::parse_query($uri_q), $args); }
		$uri = preg_replace('#\?.*#','',$uri);
		if ($args) { $uri .= '?'.http_build_query($args, '', '&'); }
		return $uri;
	}

	public static function isHTTPS($url) { return 0 === strpos($url,'https://'); }

}
